package com.scu.qingshi.dts;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scu.qingshi.domain.email.enums.EmailStatusEnum;
import com.scu.qingshi.infrastructure.dao.po.Email;
import com.scu.qingshi.infrastructure.dao.service.EmailService;
import com.scu.qingshi.infrastructure.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 发送邮件任务
 * @author qingshi
 */
@Component
public class SendEmailTask {

    @Autowired
    EmailService emailService;

    @Autowired
    EmailUtil emailUtil;

//    @Scheduled(cron = "0 2 * * * ?")
    void execute(){

        // 发送邮件
        QueryWrapper<Email> wrapper = new QueryWrapper<>();
        Page<Email> page = new Page<>(1, 200);
        wrapper.eq("status", EmailStatusEnum.INIT.name());
        Page<Email> emails = emailService.page(page,wrapper);
        emails.getRecords().forEach(email -> {
            emailUtil.sendEmail(email.getFromEmail(), email.getToEmail(), email.getTitle(),email.getContent());
        });

        // 更新数据库中的状态
        List<Integer> ids = emails.getRecords().stream().map(Email::getEmailId).collect(Collectors.toList());
        UpdateWrapper<Email> updateWrap = new UpdateWrapper<>();
        updateWrap.set("status",EmailStatusEnum.SENT.name())
                .in("email_id",ids);

        emailService.update(updateWrap);

    }


}
